//
//  GrabSinglePopViewController.m
//  YueYueSpecailCarDriver
//
//  Created by DL on 17/1/10.
//  Copyright © 2017年 黄旺鑫. All rights reserved.
//

#import "GrabSinglePopViewController.h"
#import "DLLApiManager.h"
#import <QXDriverConfiguration/QXDriverConfiguration.h>
#import <QXYueYueModels/QXYYOrderDetailModel.h>
#import <QXYueYueModels/QXYYUserPassengerModel.h>
#import "InstructionView.h"
#import <QXYueYueModels/QXYueYueModels-umbrella.h>
#import "MapGeometryCalculationManager.h"
#import "LocationManager.h"
#import "UserLocationModel.h"
#import "NavigationMap.h"
#import "iflyMSC/iflyMSC.h"
#import "IflyMSCManager.h"
#import <AMapSearchKit/AMapSearchKit.h>
#import "SendLocationModel.h"
#import "SendLocationManager.h"
#import <MAMapKit/MAMapKit.h>
#import "CommonUtility.h"
#import "MANaviRoute.h"
#import "CarImageManager.h"


#import <Mapbox/Mapbox.h>
#import <MapboxDirections/MapboxDirections-Swift.h>
#import "CustomMGLPointAnnotation.h"
#import "CustomMGLAnnotationView.h"
#import <MapboxDirections/MBRouteOptions.h>

#import "MapManager.h"


@interface GrabSinglePopViewController ()<AMapSearchDelegate , MAMapViewDelegate , MGLMapViewDelegate>
/**
 * 背景图片
 **/
@property (weak, nonatomic) IBOutlet UIImageView *backgroundImageView;
/**
 * 底部三角形图片
 **/
@property (weak, nonatomic) IBOutlet UIImageView *triangleImageView;
@property (weak, nonatomic) IBOutlet InstructionView *triangleView;

/**
 * 弹出视图
 **/
@property (weak, nonatomic) IBOutlet UIView *popView;
/**
 * 显示实时或者预约和距离
 **/
@property (weak, nonatomic) IBOutlet UILabel *distanceLabel;
/**
 * 最大的scrollView
 **/
@property (weak, nonatomic) IBOutlet UIScrollView *rootScrollView;
/**
 * 地图的scrollView
 **/
@property (weak, nonatomic) IBOutlet UIScrollView *scrollView;
/**
 * 顶部视图
 **/
@property (weak, nonatomic) IBOutlet UIView *topBackgroundView;
/**
 * 底部视图
 **/
@property (weak, nonatomic) IBOutlet UIView *bottomView;
/**
 * 滑动提示语
 **/
@property (weak, nonatomic) IBOutlet UILabel *scrollPromptLabel;
/**
 * 向下箭头
 **/
@property (weak, nonatomic) IBOutlet UIImageView *downArrowImageView;
/**
 * 向上箭头
 **/
@property (weak, nonatomic) IBOutlet UIImageView *upArrowImageView;
/**
 * 起点图片
 **/
@property (weak, nonatomic) IBOutlet UIImageView *startImageView;
/**
 * 起点
 **/
@property (weak, nonatomic) IBOutlet UILabel *originLabel;
/**
 * 起点详细位置
 **/
@property (weak, nonatomic) IBOutlet UILabel *originDetailAddressLabel;
/**
 * 终点图片
 **/
@property (weak, nonatomic) IBOutlet UIImageView *destImageView;
/**
 * 终点
 **/
@property (weak, nonatomic) IBOutlet UILabel *destAddressLabel;
/**
 * 终点详细位置
 **/
@property (weak, nonatomic) IBOutlet UILabel *destDetailAddressLabel;
/**
 * 其他标签
 **/
@property (weak, nonatomic) IBOutlet UIButton *otherLabel;
/**
 * 调度费
 **/
@property (weak, nonatomic) IBOutlet UIButton *serviceFareLabel;
/**
 * 乘客留言(给司机捎话)
 **/
@property (weak, nonatomic) IBOutlet UILabel *remarkLabel;
/**
 * 抢单失败提示语
 **/
@property (weak, nonatomic) IBOutlet UILabel *grabFailLabel;
/**
 * 抢单按钮
 **/
@property (weak, nonatomic) IBOutlet UIButton *grabButton;
/**
 * 关闭按钮
 **/
@property (weak, nonatomic) IBOutlet UIButton *backButton;


/**
 距离顶部的距离
 这个参数用于查看地图动画,默认为0,弹上去后根据约束计算
 */
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *marginTo_Top_TitleView;


/**
 目的地背景视图,如果为实时单的话隐藏,如果为预约单的话展示
 */
@property (weak, nonatomic) IBOutlet UIView *destBackView;

// 目的地背景视图顶部的距离,如果为实时单的话这里为0,如果为预约单的话这里为12
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *marginTo_Top_DestBackView;


/**
 取消订单显示的view
 */
@property (weak, nonatomic) IBOutlet UIView *cancelOrderBackView;


/**
 弹出视图顶部距离根式图的距离
 */
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *marginTo_Top_PopView;

/**
 弹出视图底部距离跟试图的距离
 */
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *marginTo_Bottom_PopView;


/**
 上滑查看地图,下滑关闭地图,在下的时候为0,在上的时候为-7.5
 */
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *marginTo_Center_BottomView;


/**
 抢单按钮的背景视图
 */
@property (weak, nonatomic) IBOutlet UIView *grabSingleButtonBackView;


/**
 不能点击倒计时label
 */
@property (weak, nonatomic) IBOutlet UILabel *canNotClickLabel;

@property(nonatomic , strong) NSTimer *timer;

// 调度费label顶部间距
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *marginTo_Top_TipLabel;


/**
 调度费label的高度
 */
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *titpLabelHeight;


/**
 乘客留言label顶部间隙
 */
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *marginTo_Top_RemarkLabel;


/**
 目的地label顶部间隙
 */
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *marginTo_Top_DestDetailLabel;


/**
 地图背景视图
 */
@property (weak, nonatomic) IBOutlet UIView *mapBackView;

/**
 可以抢单的倒计时label
 */
@property (weak, nonatomic) IBOutlet UILabel *grabLabel;


/**
 抢单按钮的标题
 */
@property (weak, nonatomic) IBOutlet UILabel *grabTitleLabel;


/**
 如果是抢单15
 如果是收到派单25
 */
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *grabOrderMarginToTop;



/// 地图视图 
//@property (weak, nonatomic) IBOutlet MAMapView *mapView;
@property (strong, nonatomic) MAMapView *mapView;

/// 起点大头针
@property(nonatomic , strong) MAPointAnnotation *startAnnotation;
/// 终点大头针
@property(nonatomic , strong) MAPointAnnotation *destinationAnnotation;

/// 线路规划搜索对象
@property(nonatomic , strong) AMapSearchAPI *searchAPI;

/// 规划的路线对象
@property(nonatomic , strong) MANaviRoute *naviRoute;


/// mapbox 加载
@property(nonatomic , assign) BOOL isLoadFinished;
/// 当前的导航路线
@property(nonatomic , strong) MBRoute *currentMapBoxRoute;
/// 当前在地图上显示的路线
@property(nonatomic , strong) MGLPolyline *currentMapboxRouteLine;

/// 起点注释
@property(nonatomic , strong) CustomMGLPointAnnotation *orginPinMapbox;
/// 终点注释
@property(nonatomic , strong) CustomMGLPointAnnotation *destPinMapbox;
/// mapbox 地图
@property(nonatomic , strong) MGLMapView *mapboxMapView;

@end

@implementation GrabSinglePopViewController
#define TriangleHeight 15
+ (instancetype)shareSelf {
    return [[UIStoryboard storyboardWithName:@"Orders" bundle:nil] instantiateViewControllerWithIdentifier:@"GrabSinglePopViewController"];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self configureDefaultAttributes];
    [self configureFillet];
    [self registerNotificationOrderState];
}

- (void)viewDidLayoutSubviews {
    [super viewDidLayoutSubviews];
        
    if ([MapManager shareManager].currentMapType == MapTypeMapBox) {
        
        if (self.isLoadFinished == NO) {
            [self initMapboxMapView];
            self.isLoadFinished = YES;
        }
    }else if ([MapManager shareManager].currentMapType == MapTypeGD) {
        
        if (self.isLoadFinished == NO) {
            
            [self configureMapView];
            self.isLoadFinished = YES;
        }
    }
}

- (void)configureDefaultAttributes {
    
    // 前三秒不能点击
    self.canNotClickLabel.backgroundColor = [UIColor lightGrayColor];
    self.grabSingleButtonBackView.userInteractionEnabled = NO;
    
    
    if (self.typeOfPushOrder == TypeOfPushOrder_Push) {
        
        self.canNotClickLabel.text = @"3";
        self.grabLabel.text = @"16";
        self.canNotClickLabel.hidden = NO;
    }else {
        
        self.grabOrderMarginToTop.constant = 25;
        self.grabSingleButtonBackView.userInteractionEnabled = YES;
        self.grabTitleLabel.font = [UIFont systemFontOfSize:18.0];
        self.canNotClickLabel.hidden = YES;
        self.grabTitleLabel.text = @"收到派单";
    }
    self.timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(canClickAction:) userInfo:nil repeats:YES];
    [[NSRunLoop mainRunLoop] addTimer:self.timer forMode: NSRunLoopCommonModes];
    
    self.backgroundImageView.image = [QXDriverConfiguration imageWithName:@"bg"];
    self.downArrowImageView.image = [QXDriverConfiguration imageWithName:@"public_guizeshuoming_xia"];
    self.upArrowImageView.image = [QXDriverConfiguration imageWithName:@"public_guizeshuoming_shang"];
    [self.backButton setImage:[QXDriverConfiguration imageWithName:@"public_jiaodan_icon_dacha"] forState:(UIControlStateNormal)];
    
    self.cancelOrderBackView.hidden = YES;
    
    self.downArrowImageView.hidden = YES;
    

    self.serviceFareLabel.layer.cornerRadius = 3.0;
    self.serviceFareLabel.layer.masksToBounds = YES;
    self.serviceFareLabel.layer.borderWidth = 0.5;
    self.serviceFareLabel.layer.borderColor = Color_bdc8f1.CGColor;
    self.grabSingleButtonBackView.layer.cornerRadius = 45.0;
    self.grabSingleButtonBackView.layer.masksToBounds = YES;
    
//    上滑查看地图
    self.scrollPromptLabel.text = KeyWord_UpSlideViewMap;
    
    [self refreshUIWithCarPoolOrderDetailModel:self.carPoolOrderDetailModel];
    
    // 设置抢单页面背景视图
    self.backgroundImageView.image = [QXDriverConfiguration imageWithName:@"bg"];
    
}


#pragma mark - 抢单倒计时
- (void)canClickAction:(NSTimer *)timer {
    
    if (self.typeOfPushOrder == TypeOfPushOrder_Push) {
        
        if ([self.canNotClickLabel.text integerValue] >= 2) {
//            dispatch_async(dispatch_get_main_queue(), ^{
//                
//                self.canNotClickLabel.text = [NSString stringWithFormat:@"%d" , ([self.canNotClickLabel.text integerValue] - 1)];
//                self.canNotClickLabel.hidden = NO;
//            });
            self.canNotClickLabel.text = [NSString stringWithFormat:@"%d" , ([self.canNotClickLabel.text integerValue] - 1)];
            self.canNotClickLabel.hidden = NO;
            
        }else {
            
            
//            dispatch_async(dispatch_get_main_queue(), ^{
//                self.canNotClickLabel.hidden = YES;
//                self.grabOrderMarginToTop.constant = 15;
//                self.grabSingleButtonBackView.userInteractionEnabled = YES;
//                self.grabTitleLabel.font = [UIFont systemFontOfSize:23.0];
//                self.grabTitleLabel.text = @"抢单";
//                self.grabLabel.text = [NSString stringWithFormat:@"%d" , ([self.grabLabel.text integerValue] - 1)];
//            });
            
            self.canNotClickLabel.hidden = YES;
            self.grabOrderMarginToTop.constant = 15;
            self.grabSingleButtonBackView.userInteractionEnabled = YES;
            self.grabTitleLabel.font = [UIFont systemFontOfSize:23.0];
            self.grabTitleLabel.text = @"抢单";
            self.grabLabel.text = [NSString stringWithFormat:@"%d" , ([self.grabLabel.text integerValue] - 1)];
            
            if ([self.grabLabel.text integerValue] <= 1) {
                
                [self dismissAction:nil];
            }
        }
    }else {
        
        
        
//        dispatch_async(dispatch_get_main_queue(), ^{
//            self.grabOrderMarginToTop.constant = 25;
//            self.grabSingleButtonBackView.userInteractionEnabled = YES;
//            self.grabTitleLabel.font = [UIFont systemFontOfSize:18.0];
//            self.canNotClickLabel.hidden = YES;
//            self.grabTitleLabel.text = @"收到派单";
//            self.grabLabel.text = [NSString stringWithFormat:@"%d" , ([self.grabLabel.text integerValue] - 1)];
//        });
        
        self.grabOrderMarginToTop.constant = 25;
        self.grabSingleButtonBackView.userInteractionEnabled = YES;
        self.grabTitleLabel.font = [UIFont systemFontOfSize:18.0];
        self.canNotClickLabel.hidden = YES;
        self.grabTitleLabel.text = @"收到派单";
        self.grabLabel.text = [NSString stringWithFormat:@"%d" , ([self.grabLabel.text integerValue] - 1)];
        
        if ([self.grabLabel.text integerValue] == 1) {
            
            [self dismissAction:nil];
        }
    }

}

// 刷新UI
- (void)refreshUIWithCarPoolOrderDetailModel:(CarPoolOrderDetailModel *)carPoolOrderDetailModel {
    
    // 隐藏订单失败view
    self.cancelOrderBackView.hidden = YES;
    
    
    // 配置出发地信息
    self.originLabel.text = carPoolOrderDetailModel.originAddress;
    self.originDetailAddressLabel.text = carPoolOrderDetailModel.originDetailAddress;
    
    // 配置即时订单与预约单信息
    if ([carPoolOrderDetailModel.typeTime isEqualToString:@"1"]) { // 1 即时订单
        
        // 配置表头信息
        CLLocationCoordinate2D point1 = CLLocationCoordinate2DMake([LocationManager shareManager].userLocationModel.userLocation.coordinate.latitude, [LocationManager shareManager].userLocationModel.userLocation.coordinate.longitude);
        CLLocationCoordinate2D point2 = CLLocationCoordinate2DMake(carPoolOrderDetailModel.originLat, carPoolOrderDetailModel.originLng);
        
        CLLocationDistance distance = [MapGeometryCalculationManager calculateTheDistanceBetweenStartMAMapPoint:point1 endMAMapPoint:point2];
        if (distance < 1000) {
            
            self.distanceLabel.text = [NSString stringWithFormat:@"实时 | 距您%.2f米" , distance];
        }else {
            
            self.distanceLabel.text = [NSString stringWithFormat:@"实时 | 距您%.2f公里" , distance / 1000.0];
        }
        
        
        // 处理间隙
        self.marginTo_Top_DestBackView.constant = 0.0;
        self.marginTo_Top_DestDetailLabel.constant = 0.0;
        
        
        // 配置目的信息
        self.marginTo_Top_DestBackView.constant = 0.0;
        self.destBackView.hidden = YES;
        self.destAddressLabel.text = @"";
        self.destDetailAddressLabel.text = @"";
    }else { // 预约单
        
        // 配置表头信息
        NSString *timeString = [self timeStampConversionTimeStringWithTimeStamp:carPoolOrderDetailModel.deparTime dateFormatter:@"HH:mm"];

        NSString *dayDescription = [self showTitleForAppointmentWithTimestamp:carPoolOrderDetailModel.deparTime / 1000];
        if (dayDescription == nil) {
            
            dayDescription = @"";
        }
        
        NSString *orderTypeStr;
        
        if ([self.carPoolOrderDetailModel.typeTime isEqualToString:@"3"]) { // 日租
            
            self.destBackView.hidden = YES;
            orderTypeStr = @"包车8小时";
        }else if ([self.carPoolOrderDetailModel.typeTime isEqualToString:@"4"]) { // 半日租
            
            self.destBackView.hidden = YES;
            orderTypeStr = @"包车4小时";
        }else {
            
            self.destBackView.hidden = NO;
            orderTypeStr = @"预约";
        }
        self.distanceLabel.text = [NSString stringWithFormat:@"%@ | %@ %@" ,orderTypeStr , dayDescription,timeString];
        
        // 处理间隙
        self.marginTo_Top_DestBackView.constant = 12.0;
        self.marginTo_Top_DestDetailLabel.constant = 5.0;
        
        // 配置目的信息
        self.marginTo_Top_DestBackView.constant = 12.0;
        self.destAddressLabel.text = carPoolOrderDetailModel.destAddress;
        self.destDetailAddressLabel.text = carPoolOrderDetailModel.destDetailAddress;
    }
    
    // 配置调度费
    if (carPoolOrderDetailModel.tip <= 0) {
        
        [self.serviceFareLabel setTitle:[NSString stringWithFormat:@"  调度费%.1f元  " , 0.0] forState:(UIControlStateNormal)];
        self.serviceFareLabel.hidden = YES;
        self.marginTo_Top_TipLabel.constant = 0.0;
        self.titpLabelHeight.constant = 0.0;
    }else {
        
        [self.serviceFareLabel setTitle:[NSString stringWithFormat:@"  调度费%.1f元  " , carPoolOrderDetailModel.tip] forState:(UIControlStateNormal)];
        self.serviceFareLabel.hidden = NO;
        self.marginTo_Top_TipLabel.constant = 16.0;
        self.titpLabelHeight.constant = 25.0;
    }
    
    
    // 配置稍话内容
    if ([carPoolOrderDetailModel.remark isKindOfClass:NULL] || carPoolOrderDetailModel.remark.length <= 0) {
        
        self.remarkLabel.text = @"";
        self.marginTo_Top_RemarkLabel.constant = 0.0;
    }else {
        
        self.remarkLabel.text = carPoolOrderDetailModel.remark;
        self.marginTo_Top_RemarkLabel.constant = 25.0;
    }

}



- (NSString *)showTitleForAppointmentWithTimestamp:(NSTimeInterval)timestamp {
    
    NSString *todayString = [self timestampToDateStringWithTimeStamp:[self getOneDayTimestampFromTodayWithDayNumber:0 delayHourTime:0] timeFormatter:@"yyyyMMdd"];
    NSString *tomorrow = [self timestampToDateStringWithTimeStamp:[self getOneDayTimestampFromTodayWithDayNumber:1 delayHourTime:0] timeFormatter:@"yyyyMMdd"];
    NSString *afterTomorrow = [self timestampToDateStringWithTimeStamp:[self getOneDayTimestampFromTodayWithDayNumber:2 delayHourTime:0] timeFormatter:@"yyyyMMdd"];
    
    NSString *nowDescription = [self timestampToDateStringWithTimeStamp:timestamp timeFormatter:@"yyyyMMdd"];
    
    NSString *outPutString;
    
    if ([nowDescription isEqualToString:todayString]) {
        
        outPutString = @"今天";
    }else if ([nowDescription isEqualToString:tomorrow]) {
        
        outPutString = @"明天";
    }else if ([nowDescription isEqualToString:afterTomorrow]) {
        
        outPutString = @"后天";
    }
    return outPutString;
}

- (NSTimeInterval)getOneDayTimestampFromTodayWithDayNumber:(NSInteger)dayNumber delayHourTime:(NSInteger)delayHourTime {
    
    NSDate *date = [NSDate dateWithTimeIntervalSinceNow:dayNumber * 24 * 60 * 60 + delayHourTime * 60 * 60];
    NSTimeInterval timeInterval = [date timeIntervalSince1970];
    
    return timeInterval;
}

- (NSString *)timestampToDateStringWithTimeStamp:(NSTimeInterval)timestamp timeFormatter:(NSString *)timeFormatter {
    
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:timeFormatter];
    NSDate *date = [NSDate dateWithTimeIntervalSince1970:timestamp];
    NSString *timeString = [dateFormatter stringFromDate:date];
    
    return timeString;
}




/**
 订单失效刷新UI

 @param subStatus 订单状态
 @param msg 订单失效返回的信息
 */
- (void)refreshUIWhenOrderInvalidWithSubStatus:(NSInteger)subStatus msg:(NSString *)msg {
    
    switch (self.typeOfPushOrder) {
        case TypeOfPushOrder_Push:
            
            self.distanceLabel.text = KeyWord_RobTheSingleError;
            break;
        case TypeOfPushOrder_Delivery:
            
            self.distanceLabel.text = KeyWord_SingleFailure;
            break;
            
        default:
            break;
    }
    
    self.cancelOrderBackView.hidden = NO;
    
    if ([msg isKindOfClass:NULL] || msg.length <= 0) {
        
        self.grabFailLabel.text = KeyWord_PassengerCancelOrder;
    }else {
        
        self.grabFailLabel.text = msg;
    }
}


/**
 时间戳转化指定格式的时间字符串

 @param timeStamp 时间戳
 @param dateFormatter 转化的时间格式
 @return 时间格式
 */
- (NSString *)timeStampConversionTimeStringWithTimeStamp:(NSTimeInterval)timeStamp dateFormatter:(NSString *)dateFormatter {
    
    NSDate *currentDate = [NSDate dateWithTimeIntervalSince1970:timeStamp / 1000.0];
    NSDateFormatter *formatter = [NSDateFormatter new];
    [formatter setDateFormat:dateFormatter];
    NSString *timeString = [formatter stringFromDate:currentDate];
    
    return timeString;
}


/**
 注册通知获取订单的状态
 */
- (void)registerNotificationOrderState {
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(dealOrderState:) name:LongLinkNoftificationName_PassengerCancelOrder object:nil];  // 乘客取消订单
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(dealOrderState:) name:LongLinkNoftificationName_OrderChanged object:nil]; // 订单被改派
}


/**
 处理订单信息
 */
- (void)dealOrderState:(NSNotification *)aNotification {
    
    if ([aNotification.name isEqualToString:LongLinkNoftificationName_PassengerCancelOrder] || [aNotification.name isEqualToString:LongLinkNoftificationName_OrderChanged] || [aNotification.name isEqualToString:LongLinkNoftificationName_OrderBackShutdown]) {
        
        
        // 订单状态代码
        NSInteger opCode = [aNotification.object[@"opCode"] integerValue];
        
        // 订单ID
        NSString *orderUuid = [NSString stringWithFormat:@"%@" , aNotification.object[@"data"][@"orderUuid"]];
        
        if ([orderUuid isEqualToString:self.carPoolOrderDetailModel.uuid]) { // 判断收到的通知订单和正在处理的订单是否是同一个订单
            
            if (opCode == LongLinkCode_Order_Passenger_Cancel || opCode == LongLinkCode_Order_Changed || opCode == LongLinkCode_Order_BackgroundShutdown) { // 乘客取消订单, 订单改派 , 后台关闭
                
                [self refreshUIWhenOrderInvalidWithSubStatus:0 msg:aNotification.object[@"data"][@"content"]];
                
            }
        }
    }
}



/**
 配置圆角
 */
- (void)configureFillet {
    
    self.grabButton.layer.cornerRadius = self.grabButton.frame.size.height / 2.0;
    self.grabButton.layer.masksToBounds = YES;
    
    self.popView.layer.cornerRadius = 5.0;
    self.popView.layer.masksToBounds = YES;
    
    self.startImageView.layer.cornerRadius = 4.0;
    self.startImageView.layer.masksToBounds = YES;
    
    self.destImageView.layer.cornerRadius = 4.0;
    self.destImageView.layer.masksToBounds = YES;
    
    self.triangleView.trianglePoint = CGPointMake(([UIScreen mainScreen].bounds.size.width - 60) / 2.0, self.popView.frame.size.height);
    
    self.popView.layer.mask = [self creatMaskView];
}
/**
 绘画遮罩图形
 */
- (CAShapeLayer *)creatMaskView {

    CAShapeLayer *shapeLayer = [CAShapeLayer layer];
    
    UIBezierPath *bezierPath = [UIBezierPath bezierPath];
    
    //    bezierPath.lineCapStyle = kCGLineJoinRound;
    
    CGFloat width = [UIScreen mainScreen].bounds.size.width - 60;
    CGFloat height = [UIScreen mainScreen].bounds.size.height - 220;
    
    CGFloat rectangleFillet = 5.0;
    CGFloat lineWidth = 0.0;
    CGFloat triangleHeight = TriangleHeight;
    
    CGFloat triangleFillet = 3.0;
    
    CGPoint trianglePoint = CGPointMake(width / 2.0, height);
    
    // 右上角圆角中线点
    CGPoint topRightCornerPoint = CGPointMake(width - rectangleFillet - lineWidth / 2.0, rectangleFillet + lineWidth / 2.0);
    // 右下角圆角中线点
    CGPoint bottomRightCornerPoint = CGPointMake(width - rectangleFillet - lineWidth / 2.0, height - rectangleFillet - lineWidth / 2.0 - triangleHeight);
    // 左下角圆角中线点
    CGPoint bottomLeftCornerPoint = CGPointMake(lineWidth / 2.0 + rectangleFillet, height - rectangleFillet - lineWidth / 2.0 - triangleHeight);
    // 左上角圆角中线点
    CGPoint topLeftCornerPoint = CGPointMake(lineWidth / 2.0 + rectangleFillet, rectangleFillet + lineWidth / 2.0);
    // 绘制三角形的起始点
    CGPoint originPoint = CGPointMake(trianglePoint.x + triangleHeight * tan(M_PI / 6), height - triangleHeight - lineWidth / 2.0);
    
    [bezierPath moveToPoint:originPoint];
    [bezierPath addArcWithCenter:CGPointMake(trianglePoint.x, height - lineWidth / 2.0 - triangleFillet) radius:triangleFillet startAngle:M_PI / 3 endAngle:M_PI / 3 * 2 clockwise:YES];
    [bezierPath addLineToPoint:CGPointMake(trianglePoint.x - triangleHeight * tan(M_PI / 6), height - triangleHeight - lineWidth / 2.0)];
    [bezierPath addArcWithCenter:bottomLeftCornerPoint radius:rectangleFillet startAngle:M_PI / 2.0 endAngle:M_PI clockwise:YES];
    [bezierPath addArcWithCenter:topLeftCornerPoint radius:rectangleFillet startAngle:M_PI endAngle:M_PI / 2.0 * 3 clockwise:YES];
    [bezierPath addArcWithCenter:topRightCornerPoint radius:rectangleFillet startAngle:M_PI / 2.0 * 3 endAngle:0 clockwise:YES];
    [bezierPath addArcWithCenter:bottomRightCornerPoint radius:rectangleFillet startAngle:0 endAngle:M_PI / 2.0 clockwise:YES];
    [bezierPath addLineToPoint:originPoint];
    
    shapeLayer.path = bezierPath.CGPath;
    
    return shapeLayer;

}



// 抢单按钮Action
- (IBAction)grabSingleOrderAction:(UIButton *)sender {
    
    sender.userInteractionEnabled = NO;
    self.grabButton.userInteractionEnabled = NO;
    if (self.typeOfPushOrder == TypeOfPushOrder_Push) { // 如果推送的是可抢订单,那么进行抢单请求
        
        [self grabTheOrdersCarPoolOrderDetailModel:self.carPoolOrderDetailModel];
    }else { // 如果是派单那么消失
        
        [[NSNotificationCenter defaultCenter] postNotificationName:NotificationName_GrabRealTimeOrder object:nil]; // 发送抢到即时单的通知
        [self dismissAction:nil];
    }
}

#pragma mark - 配置 mapbox 的地图
- (void)initMapboxMapView {
    
    self.mapboxMapView = [[MGLMapView alloc] initWithFrame:CGRectMake(0, 0, self.mapBackView.frame.size.width, self.mapBackView.frame.size.height)];
    self.mapboxMapView.delegate = self;
    self.mapboxMapView.showsUserLocation = YES;
    
    
    [self.mapboxMapView setUserTrackingMode:(MGLUserTrackingModeFollow) animated:YES];
    [self.mapBackView addSubview:self.mapboxMapView];
    
    self.mapboxMapView.autoresizingMask = UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleWidth;
    [self.mapboxMapView bringSubviewToFront:self.mapBackView];
    
    [self beginMapboxRouteLineConfigurations];
    
}

#pragma mapbox 开始 Mapbox 地图的路线规划配置
- (void)beginMapboxRouteLineConfigurations {
    
    if (self.mapboxMapView.userLocation.coordinate.latitude == 0 || self.mapboxMapView.userLocation.coordinate.longitude == 0) {
        
        dispatch_async(dispatch_get_main_queue(), ^{
            
            MBProgressHUD *mb = [MBProgressHUD showWithText:@"定位失败" onView:self.view hiddenDuration:2.0];
            mb.userInteractionEnabled = NO;
        });
        return;
    }
    
    CustomMGLPointAnnotation *orginPin = [[CustomMGLPointAnnotation alloc] init];
    orginPin.identifier = @"起点";
    orginPin.title = @"起点";
    
    CustomMGLPointAnnotation *destPin = [[CustomMGLPointAnnotation alloc] init];
    destPin.identifier = @"终点";
    destPin.title = @"终点";
    if ([self.carPoolOrderDetailModel.typeTime integerValue] == OrderPushTypeTimely) { // 及时单

        
        orginPin.coordinate = CLLocationCoordinate2DMake([LocationManager shareManager].userLocationModel.userLocation.coordinate.latitude, [LocationManager shareManager].userLocationModel.userLocation.coordinate.longitude);
        
        destPin.coordinate = CLLocationCoordinate2DMake(self.carPoolOrderDetailModel.originLat, self.carPoolOrderDetailModel.originLng);
        
    } else if ([self.carPoolOrderDetailModel.typeTime integerValue] == OrderPushTypeDaiyRental || [self.carPoolOrderDetailModel.typeTime integerValue] == OrderPushTypeHalfDayRent) { // 日租班半日租
        
        orginPin.coordinate = CLLocationCoordinate2DMake([LocationManager shareManager].userLocationModel.userLocation.coordinate.latitude, [LocationManager shareManager].userLocationModel.userLocation.coordinate.longitude);
        
        destPin.coordinate = CLLocationCoordinate2DMake(self.carPoolOrderDetailModel.originLat, self.carPoolOrderDetailModel.originLng);
        
    }else {  // 普通预约单
        
        orginPin.coordinate = CLLocationCoordinate2DMake(self.carPoolOrderDetailModel.originLat, self.carPoolOrderDetailModel.originLng);
        
        destPin.coordinate = CLLocationCoordinate2DMake(self.carPoolOrderDetailModel.destLat, self.carPoolOrderDetailModel.destLng);
    }
    
    NSArray<CustomMGLPointAnnotation *>* pinArr = @[orginPin , destPin];
    [self.mapboxMapView addAnnotations:pinArr];
    
    MBWaypoint *orginWaypoint = [[MBWaypoint alloc] initWithCoordinate:orginPin.coordinate coordinateAccuracy:(kCLLocationAccuracyBest) name:@"起点"];
    MBWaypoint *destWaypoint = [[MBWaypoint alloc] initWithCoordinate:destPin.coordinate coordinateAccuracy:(kCLLocationAccuracyBest) name:@"终点"];
    NSArray<MBWaypoint *>* waypoints = @[orginWaypoint , destWaypoint];
    [self mapBoxDrawRouteLinePass:waypoints];
    
    
}


/// 规划地图并展示地图
- (void)mapBoxDrawRouteLinePass:(NSArray <MBWaypoint *>*)wayPoints {
    
    if (wayPoints.count < 2) {
        
        return;
    }
    
    MBRouteOptions *options = [[MBRouteOptions alloc] initWithWaypoints:wayPoints profileIdentifier:(MBDirectionsProfileIdentifierAutomobileAvoidingTraffic)];
    options.includesSteps = true;
    
    MBDirections *directions = [MBDirections sharedDirections];
    
    
    __weak typeof(self) weakSelf = self;
    NSURLSessionDataTask *task = [directions calculateDirectionsWithOptions:options completionHandler:^(NSArray<MBWaypoint *> * _Nullable wayPoints, NSArray<MBRoute *> * _Nullable routes, NSError * _Nullable error) {
        
        __strong typeof(self) strongSelf = weakSelf;
        
        if (error) {
            
            return;
        }
        
        
        if (routes.count > 0) {
            
            MBRoute *route = routes.firstObject;
            
            if (route.coordinateCount > 0) {
                
                // Convert the route’s coordinates into a polyline.
                CLLocationCoordinate2D *routeCoordinates = malloc(route.coordinateCount * sizeof(CLLocationCoordinate2D));
                [route getCoordinates:routeCoordinates];
                MGLPolyline *routeLine = [MGLPolyline polylineWithCoordinates:routeCoordinates count:route.coordinateCount];
                
//                [strongSelf.mapboxMapView addAnnotation:routeLine];
                [strongSelf.mapboxMapView addOverlay:routeLine];
                [strongSelf.mapboxMapView setVisibleCoordinates:routeCoordinates count:route.coordinateCount edgePadding:UIEdgeInsetsMake(30, 30, 40, 30) animated:YES];
                free(routeCoordinates);
            }
        }
        
    }];
    [task resume];
}



#pragma mark - 配置高德地图
- (void)configureMapView {
    
    self.mapView = [[MAMapView alloc] initWithFrame:CGRectMake(0, 0, self.mapBackView.frame.size.width, self.mapBackView.frame.size.height)];
    [self.mapBackView addSubview:self.mapView];
    self.mapView.autoresizingMask = UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleWidth;
    self.mapView.delegate = self;
    self.startAnnotation = [[MAPointAnnotation alloc] init];
    self.destinationAnnotation = [[MAPointAnnotation alloc] init];
    self.mapView.userInteractionEnabled = YES;
    self.mapView.showsUserLocation = YES;
    
    if (![LocationManager shareManager].userLocationModel) {
        
        dispatch_async(dispatch_get_main_queue(), ^{
            
            MBProgressHUD *mb = [MBProgressHUD showWithText:@"地图定位失败" onView:self.view hiddenDuration:2.0];
            mb.userInteractionEnabled = NO;
        });
        
    }else {
        
        [self beginRoutePlanning];
    }
}

#pragma mark - 开始线路规划
- (void)beginRoutePlanning {
    
    MAPointAnnotation *annotation_Origin;
    MAPointAnnotation *annotation_Dest;
    if ([self.carPoolOrderDetailModel.typeTime isEqualToString:@"1"]) { // 即时单
        

        annotation_Origin = [[MAPointAnnotation alloc] init];
        annotation_Origin.title = @"起点";
        annotation_Origin.coordinate = CLLocationCoordinate2DMake([LocationManager shareManager].userLocationModel.userLocation.coordinate.latitude, [LocationManager shareManager].userLocationModel.userLocation.coordinate.longitude);
        
        annotation_Dest = [[MAPointAnnotation alloc] init];
        annotation_Dest.title = @"终点";
        annotation_Dest.coordinate = CLLocationCoordinate2DMake(self.carPoolOrderDetailModel.originLat, self.carPoolOrderDetailModel.originLng);
        
        
    }else {
        
        if ([self.carPoolOrderDetailModel.typeTime isEqualToString:@"3"] || [self.carPoolOrderDetailModel.typeTime isEqualToString:@"4"]) { // 预约单,日租/半日租
            
            annotation_Origin = [[MAPointAnnotation alloc] init];
            annotation_Origin.title = @"起点";
            annotation_Origin.coordinate = CLLocationCoordinate2DMake([LocationManager shareManager].userLocationModel.userLocation.coordinate.latitude, [LocationManager shareManager].userLocationModel.userLocation.coordinate.longitude);
            
            annotation_Dest = [[MAPointAnnotation alloc] init];
            annotation_Dest.title = @"终点";
            annotation_Dest.coordinate = CLLocationCoordinate2DMake(self.carPoolOrderDetailModel.originLat, self.carPoolOrderDetailModel.originLng);
            
        }else { // 普通预约单
            
            annotation_Origin = [[MAPointAnnotation alloc] init];
            annotation_Origin.title = @"起点";
            annotation_Origin.coordinate = CLLocationCoordinate2DMake(self.carPoolOrderDetailModel.originLat, self.carPoolOrderDetailModel.originLng);
            
            annotation_Dest = [[MAPointAnnotation alloc] init];
            annotation_Dest.title = @"终点";
            annotation_Dest.coordinate = CLLocationCoordinate2DMake(self.carPoolOrderDetailModel.destLat, self.carPoolOrderDetailModel.destLng);
        }
    }
    
    NSArray *annotationArray = @[annotation_Origin , annotation_Dest];
    [self.mapView addAnnotations:annotationArray];
    
    AMapDrivingRouteSearchRequest *naviRequest = [[AMapDrivingRouteSearchRequest alloc] init];
    
    naviRequest.requireExtension = YES;
    naviRequest.strategy = 0;
    
    AMapGeoPoint *orignPoint = [AMapGeoPoint locationWithLatitude:annotation_Origin.coordinate.latitude longitude:annotation_Origin.coordinate.longitude];
    naviRequest.origin = orignPoint;
    
    AMapGeoPoint *destPoint = [AMapGeoPoint locationWithLatitude:annotation_Dest.coordinate.latitude longitude:annotation_Dest.coordinate.longitude];
    naviRequest.destination = destPoint;
    
    if (!self.searchAPI) {
        
        self.searchAPI = [[AMapSearchAPI alloc] init];
        self.searchAPI.delegate = self;
    }
    
    [self.searchAPI AMapDrivingRouteSearch:naviRequest];
}




#pragma mark - AMapSearchDelegate
- (void)AMapSearchRequest:(id)request didFailWithError:(NSError *)error
{
    NSLog(@"路线规划失败");
}

/* 路径规划搜索回调. */
- (void)onRouteSearchDone:(AMapRouteSearchBaseRequest *)request response:(AMapRouteSearchResponse *)response
{
    if (response.route == nil)
    {
        return;
    }
    
    AMapPath *nowRoute = response.route.paths.firstObject;
    
    if (response.count > 0)
    {
        [self presentCurrentCourceWithRouteInfo:nowRoute];
    }
}

- (void)presentCurrentCourceWithRouteInfo:(AMapPath *)route {
    
    MANaviAnnotationType type = MANaviAnnotationTypeDrive;
    
    
    if ([self.carPoolOrderDetailModel.typeTime isEqualToString:@"1"]) { // 即时单
        
        // 当前需要展示的路线
        self.naviRoute = [MANaviRoute naviRouteForPath:route withNaviType:type showTraffic:NO startPoint:[AMapGeoPoint locationWithLatitude:[LocationManager shareManager].userLocationModel.userLocation.coordinate.latitude longitude:[LocationManager shareManager].userLocationModel.userLocation.coordinate.longitude] endPoint:[AMapGeoPoint locationWithLatitude:self.carPoolOrderDetailModel.originLat longitude:self.carPoolOrderDetailModel.originLng]];
        
    }else {
        

        
        if ([self.carPoolOrderDetailModel.typeTime isEqualToString:@"3"] || [self.carPoolOrderDetailModel.typeTime isEqualToString:@"4"]) { // 预约单,日租/半日租
            
            
            self.naviRoute = [MANaviRoute naviRouteForPath:route withNaviType:type showTraffic:NO startPoint:[AMapGeoPoint locationWithLatitude:[LocationManager shareManager].userLocationModel.userLocation.coordinate.latitude longitude:[LocationManager shareManager].userLocationModel.userLocation.coordinate.longitude] endPoint:[AMapGeoPoint locationWithLatitude:self.carPoolOrderDetailModel.originLat longitude:self.carPoolOrderDetailModel.originLng]];
        }else { // 普通预约单
            
            self.naviRoute = [MANaviRoute naviRouteForPath:route withNaviType:type showTraffic:NO startPoint:[AMapGeoPoint locationWithLatitude:self.carPoolOrderDetailModel.originLat longitude:self.carPoolOrderDetailModel.originLng] endPoint:[AMapGeoPoint locationWithLatitude:self.carPoolOrderDetailModel.destLat longitude:self.carPoolOrderDetailModel.destLng]];
        }
    }
    
    
    self.naviRoute.routeColor = Color_3585ff; // 路线颜色
    
    
    [self.naviRoute addToMapView:self.mapView]; // 将路线添加到地图
    
    self.mapView.showsUserLocation = YES;
    self.mapView.userTrackingMode = MAUserTrackingModeFollow;
    self.mapView.showTraffic = YES;
    
    dispatch_async(dispatch_get_main_queue(), ^{
        
        [self.mapView setVisibleMapRect:[CommonUtility mapRectForOverlays:self.naviRoute.routePolylines] edgePadding:UIEdgeInsetsMake(50, 50, 50, 50) animated:YES];
    });
    
}



#pragma mark - 地图 代理 方法

static NSString *DriverIdentifier = @"Driver";
static NSString *PinIdentifier = @"Annotation";
#if MapTypeMicro == 1 // 高德地图
- (MAAnnotationView *)mapView:(MAMapView *)mapView viewForAnnotation:(id<MAAnnotation>)annotation
{
    
    
    if ([annotation isKindOfClass:[MAUserLocation class]])
    {
        
        MAAnnotationView *driverLocation = [mapView dequeueReusableAnnotationViewWithIdentifier:DriverIdentifier];
        
        if (driverLocation == nil) {
            
            driverLocation = [[MAAnnotationView alloc] initWithAnnotation:annotation
                                                          reuseIdentifier:DriverIdentifier];
        }
        
        driverLocation.image = [CarImageManager getCarImage];
        
        return driverLocation;
    }
    
    
    if ([annotation isKindOfClass:[MAPointAnnotation class]])
    {
        
        MAAnnotationView *poiAnnotationView = (MAAnnotationView*)[self.mapView dequeueReusableAnnotationViewWithIdentifier:PinIdentifier];
        if (poiAnnotationView == nil)
        {
            poiAnnotationView = [[MAAnnotationView alloc] initWithAnnotation:annotation
                                                             reuseIdentifier:PinIdentifier];
        }
        
        poiAnnotationView.canShowCallout = YES;
        
        if ([[annotation title] isEqualToString:@"起点"]) {
            
            poiAnnotationView.image = [QXDriverConfiguration imageWithName:@"public_pic_qidian"];
            
        }else if([[annotation title] isEqualToString:@"终点"])
        {
            
            poiAnnotationView.image = [QXDriverConfiguration imageWithName:@"public_pic_zhongdian"];
        }
        
        return poiAnnotationView;
    }
    
    
    return nil;
}

#elif MapTypeMicro == 2 // MapBox 地图

- (MGLAnnotationView *)mapView:(MGLMapView *)mapView viewForAnnotation:(id<MGLAnnotation>)annotation {
    
    
    if ([annotation isKindOfClass:[MGLUserLocation class]]) {
        
        MGLUserLocationAnnotationView *userAnnotationView = [mapView dequeueReusableAnnotationViewWithIdentifier:DriverIdentifier];
        
        if (userAnnotationView == nil) {
            
            userAnnotationView = [[MGLUserLocationAnnotationView alloc] initWithReuseIdentifier:DriverIdentifier];
//            userAnnotationView.userLocation.locatio
            UIImageView *userImageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 30, 30)];
            [userAnnotationView addSubview:userImageView];
            userImageView.image = [CarImageManager getCarImage];
            userImageView.layer.cornerRadius = userImageView.frame.size.height / 2.0;
            userImageView.layer.masksToBounds = YES;
            userImageView.backgroundColor = [UIColor clearColor];
            userImageView.contentMode = UIViewContentModeCenter;
        }
        
        return userAnnotationView;
    }
    

    
    if ([annotation isKindOfClass:[CustomMGLPointAnnotation class]]) {
        
        CustomMGLAnnotationView *annotationView = (CustomMGLAnnotationView *)[mapView dequeueReusableAnnotationViewWithIdentifier:PinIdentifier];
        
        if (annotationView == nil) {
            
            annotationView = [[CustomMGLAnnotationView alloc] initWithReuseIdentifier:PinIdentifier];
            annotationView.frame = CGRectMake(0, 0, 30, 30);
        }
        
        CustomMGLPointAnnotation *customPointAnnotation = (CustomMGLPointAnnotation *)annotation;
        
        if (customPointAnnotation != nil) {
            
            annotationView.backgroundColor = [UIColor clearColor];
            if ([customPointAnnotation.identifier isEqualToString:@"起点"]) {
                
                annotationView.imageView.image = [QXDriverConfiguration imageWithName:@"public_pic_qidian"];
                
            }else if ([customPointAnnotation.identifier isEqualToString:@"终点"]) {
                
                annotationView.imageView.image = [QXDriverConfiguration imageWithName:@"public_pic_zhongdian"];
            }
        }
        
        return annotationView;
    }

    return nil;
}

#endif



- (MAOverlayRenderer *)mapView:(MAMapView *)mapView rendererForOverlay:(id<MAOverlay>)overlay
{
    if ([overlay isKindOfClass:[LineDashPolyline class]])
    {
        MAPolylineRenderer *polylineRenderer = [[MAPolylineRenderer alloc] initWithPolyline:((LineDashPolyline *)overlay).polyline];
        polylineRenderer.lineWidth   = 8;
        polylineRenderer.lineDash = YES;
        polylineRenderer.lineCapType = kMALineCapRound;
        polylineRenderer.lineJoinType = kMALineJoinRound;
        polylineRenderer.strokeColor = [UIColor redColor];
        
        return polylineRenderer;
    }
    if ([overlay isKindOfClass:[MANaviPolyline class]])
    {
        MANaviPolyline *naviPolyline = (MANaviPolyline *)overlay;
        MAPolylineRenderer *polylineRenderer = [[MAPolylineRenderer alloc] initWithPolyline:naviPolyline.polyline];
        
        polylineRenderer.lineWidth = 8;
        polylineRenderer.lineCapType = kMALineCapRound;
        polylineRenderer.lineJoinType = kMALineJoinRound;
        if (naviPolyline.type == MANaviAnnotationTypeWalking)
        {
            polylineRenderer.strokeColor = self.naviRoute.walkingColor;
        }
        else if (naviPolyline.type == MANaviAnnotationTypeRailway)
        {
            polylineRenderer.strokeColor = self.naviRoute.railwayColor;
        }
        else
        {
            polylineRenderer.strokeColor = self.naviRoute.routeColor;
        }
        
        return polylineRenderer;
    }
    if ([overlay isKindOfClass:[MAMultiPolyline class]])
    {
        MAMultiColoredPolylineRenderer * polylineRenderer = [[MAMultiColoredPolylineRenderer alloc] initWithMultiPolyline:overlay];
        
        polylineRenderer.lineWidth = 10;
        polylineRenderer.strokeColors = [self.naviRoute.multiPolylineColors copy];
        polylineRenderer.gradient = YES;
        polylineRenderer.lineCapType = kMALineCapRound;
        polylineRenderer.lineJoinType = kMALineJoinRound;
        return polylineRenderer;
    }
    
    return nil;
}



- (void)resetButAction:(UIButton *)sender {
    

}

/**
 重新绘制地图路线
 */
- (void)reDrawMapRoute {
    
    AMapGeoPoint *startPoint;
    AMapGeoPoint*endPoint;
    if ([self.carPoolOrderDetailModel.typeTime isEqualToString:@"1"]) { // 即时单
        
        startPoint = [AMapGeoPoint locationWithLatitude:[LocationManager shareManager].userLocationModel.userLocation.coordinate.latitude longitude:[LocationManager shareManager].userLocationModel.userLocation.coordinate.longitude];
        
        endPoint = [AMapGeoPoint locationWithLatitude:self.carPoolOrderDetailModel.originLat longitude:self.carPoolOrderDetailModel.originLng];
        
    }else {
        
        [AMapGeoPoint locationWithLatitude:self.carPoolOrderDetailModel.destLat longitude:self.carPoolOrderDetailModel.destLng];
        
        if ([self.carPoolOrderDetailModel.typeTime isEqualToString:@"3"] || [self.carPoolOrderDetailModel.typeTime isEqualToString:@"4"]) { // 预约单,日租/半日租
            
            startPoint = [AMapGeoPoint locationWithLatitude:[LocationManager shareManager].userLocationModel.userLocation.coordinate.latitude longitude:[LocationManager shareManager].userLocationModel.userLocation.coordinate.longitude];
            endPoint = [AMapGeoPoint locationWithLatitude:self.carPoolOrderDetailModel.originLat longitude:self.carPoolOrderDetailModel.originLng];
        }else { // 普通预约单
            
            startPoint = [AMapGeoPoint locationWithLatitude:self.carPoolOrderDetailModel.originLat longitude:self.carPoolOrderDetailModel.originLng];
            endPoint = [AMapGeoPoint locationWithLatitude:self.carPoolOrderDetailModel.destLat longitude:self.carPoolOrderDetailModel.destLng];
        }
    }

}




#pragma mark - switpAction
- (IBAction)swipeViewMapAction:(UISwipeGestureRecognizer *)sender {
    
    if (sender.direction == UISwipeGestureRecognizerDirectionUp) {
        
        
        
        [UIView animateWithDuration:0.3 delay:0.0 options:(UIViewAnimationOptionCurveEaseInOut) animations:^{
            
            self.upArrowImageView.hidden = YES;
            self.downArrowImageView.hidden = NO;
            self.marginTo_Top_TitleView.constant = -([UIScreen mainScreen].bounds.size.height - self.marginTo_Top_PopView.constant - self.marginTo_Bottom_PopView.constant - 70);
            self.marginTo_Center_BottomView.constant = -7.5;
            
            [self.view layoutIfNeeded];
        } completion:^(BOOL finished) {
            
            self.scrollPromptLabel.text = KeyWord_DownSlideCloseMap;
        }];

    }
    
    if (sender.direction == UISwipeGestureRecognizerDirectionDown) {
        
        
        [UIView animateWithDuration:0.3 delay:0.0 options:(UIViewAnimationOptionCurveEaseInOut) animations:^{
            
            self.upArrowImageView.hidden = NO;
            self.downArrowImageView.hidden = YES;
            self.marginTo_Top_TitleView.constant = 0;
            self.marginTo_Center_BottomView.constant = 0;
            [self.view layoutIfNeeded];
        } completion:^(BOOL finished) {
            
            self.scrollPromptLabel.text = KeyWord_UpSlideViewMap;
        }];
        
    }
}

#pragma mark - disMiss
- (IBAction)dismissAction:(UIButton *)sender {
    
    dispatch_async(dispatch_get_main_queue(), ^{

        [self.timer setFireDate:[NSDate distantFuture]];  // 关闭定时器
        [self.timer invalidate];
        self.timer = nil;
        [self dismissVC];
    });
}

- (void)dismissVC {
    

    [self dismissViewControllerAnimated:YES completion:nil];
    
}
- (void)dealloc {
    
    
    NSLog(@"销毁内存地址: %p" , self);
    NSLog(@"抢单页面销毁了");
}

#pragma mark -抢单请求
- (void)grabTheOrdersCarPoolOrderDetailModel:(CarPoolOrderDetailModel *)carPoolOrderDetailModel {
    
    dispatch_async(dispatch_get_main_queue(), ^{
        
        MBProgressHUD *mb = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
        mb.userInteractionEnabled = YES;
    });
    
    __weak typeof(self) weakSelf = self;
    NSMutableDictionary *dic = [NSMutableDictionary dictionary];
    [dic setValue:carPoolOrderDetailModel.uuid forKey:@"orderUuid"];
    [DLLApiManager grabTheOrderWithParameters:dic success:^(id data) {
        
        __strong typeof(self) strongSelf = weakSelf;
        dispatch_async(dispatch_get_main_queue(), ^{
            
            IflyMSCManager *iflyMSCManager = [IflyMSCManager startSyntheticSpeechWithText:NetWork_Message];
            [iflyMSCManager.iFlySpeechSynthesizer setParameter:[NSString stringWithFormat:@"80"] forKey:[IFlySpeechConstant SPEED]];
            [MBProgressHUD hideHUDForView:self.view animated:YES];
        });
        
        if (NetWork_Success) {
        
            if ([data[@"data"][@"typeTime"] integerValue] == 1) { // 即时订单
                
                /// 主线程
                dispatch_async(dispatch_get_main_queue(), ^{
                    
                    dispatch_async(dispatch_get_main_queue(), ^{
                        
                        NSMutableDictionary *obj = [NSMutableDictionary dictionary];
                        QXYYOrderDetailModel *orderDetailModel = [QXYYOrderDetailModel QXYY_objectWithKeyValues:data[@"data"]];
                        
                        // 告知服务器接到订单
                        [[SendLocationManager shareManager] configureModelInfoOfOrdersAndSendLocationInfoWithOrderUuid:orderDetailModel.uuid];
                        
                        
                        QXYYUserPassengerModel *userPassengerModel = [QXYYUserPassengerModel QXYY_objectWithKeyValues:data[@"data"][@"passenger"]];
                        [obj setValue:orderDetailModel forKey:@"QXYYOrderDetailModel"];
                        [obj setValue:userPassengerModel forKey:@"QXYYUserPassengerModel"];
                        [[NSNotificationCenter defaultCenter] postNotificationName:NotificationName_GrabRealTimeOrder object:nil]; // 发送抢到即时单的通知
                        
                        [strongSelf performSelector:@selector(pushIntoOrderDetail_RealTime:) withObject:obj afterDelay:0.0];
                    });
                });
            }else if ([data[@"data"][@"typeTime"] integerValue] == 2) { // 预约订单
                /// 主线程
                dispatch_async(dispatch_get_main_queue(), ^{

                    NSMutableDictionary *obj = [NSMutableDictionary dictionary];
                    QXYYOrderDetailModel *orderDetailModel = [QXYYOrderDetailModel QXYY_objectWithKeyValues:data[@"data"]];
                    
                    // 告知服务器接到订单
                    [[SendLocationManager shareManager] configureModelInfoOfOrdersAndSendLocationInfoWithOrderUuid:orderDetailModel.uuid];
                    
                    QXYYUserPassengerModel *userPassengerModel = [QXYYUserPassengerModel QXYY_objectWithKeyValues:data[@"data"][@"passenger"]];
                    [obj setValue:orderDetailModel forKey:@"QXYYOrderDetailModel"];
                    [obj setValue:userPassengerModel forKey:@"QXYYUserPassengerModel"];

                    [strongSelf performSelector:@selector(pushIntoOrderDetail_AppointTime:) withObject:obj afterDelay:0.0];
                });
            }else if ([data[@"data"][@"typeTime"] integerValue] == 3 || [data[@"data"][@"typeTime"] integerValue] == 4) { // 日租/半日租
                
                /// 主线程
                dispatch_async(dispatch_get_main_queue(), ^{
                    
                    NSMutableDictionary *obj = [NSMutableDictionary dictionary];
                    QXYYOrderDetailModel *orderDetailModel = [QXYYOrderDetailModel QXYY_objectWithKeyValues:data[@"data"]];
                    
                    // 告知服务器接到订单
                    [[SendLocationManager shareManager] configureModelInfoOfOrdersAndSendLocationInfoWithOrderUuid:orderDetailModel.uuid];
                    
                    QXYYUserPassengerModel *userPassengerModel = [QXYYUserPassengerModel QXYY_objectWithKeyValues:data[@"data"][@"passenger"]];
                    [obj setValue:orderDetailModel forKey:@"QXYYOrderDetailModel"];
                    [obj setValue:userPassengerModel forKey:@"QXYYUserPassengerModel"];
                    
                    [strongSelf performSelector:@selector(pushIntoOrderDetail_AppointTime:) withObject:obj afterDelay:0.0];
                });
            }
        }else {
            /// 主线程
            dispatch_async(dispatch_get_main_queue(), ^{
                
                [strongSelf refreshUIWhenOrderInvalidWithSubStatus:0 msg:data[@"msg"]];
                [strongSelf.timer setFireDate:[NSDate distantFuture]];  // 关闭定时器
                [strongSelf.timer invalidate];
                strongSelf.timer = nil;
                strongSelf.canNotClickLabel.hidden = YES;
                
            });
        }
        
    } failure:^(NSError *error) {
        dispatch_async(dispatch_get_main_queue(), ^{
            __strong typeof(self) strongSelf = weakSelf;
            strongSelf.grabButton.userInteractionEnabled = YES; // 如果抢到单为NO,不让再点击抢单页面,如果抢单网络挂掉,还可以继续抢
            [MBProgressHUD hideHUDForView:strongSelf.view animated:YES];
            MBProgressHUD *mb = [MBProgressHUD showWithText:NetWorkNotToForce onView:strongSelf.view hiddenDuration:1];
            mb.userInteractionEnabled = YES;
        });
    }];
}


/**
 这里处理实时订单
 */
- (void)pushIntoOrderDetail_RealTime:(id)obj {
    
    [[NSNotificationCenter defaultCenter] postNotificationName:NotificationName_GrabRealTimeOrder object:obj];
    [self dismissAction:nil];
}

- (void)pushIntoOrderDetail_AppointTime:(id)obj {
    
    [[NSNotificationCenter defaultCenter] postNotificationName:NotificationName_GrabAppointTimeOrder object:obj];
    [self dismissAction:nil];
}





- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
